<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-08-16 15:03:23
 * @version $Id$
 */
namespace app\employee\controller;
use think\Db;
use think\Request;
use think\Paginator;
use think\Config;
use Wx\Wxpay\WxPaysdk;
use think\Log;

class Shipping extends Base {
    
    /**
     * 配送商品列表
     * @return [type] [description]
     */
    function index(){
    	$delivery_id = $this->uid;
    	$res = Db::table('sdzx_shipping')
    	->alias('s')
    	->join('sdzx_order o','s.order_id=o.order_id')
    	->join('sdzx_shop sp','o.user_id=sp.user_id','left')
    	->field('s.*,o.receiver_name,o.receiver_mobile,o.receiver_address,o.receiver_pcd,DATE(o.pay_time) as time,o.order_no,o.remarks,sp.shop_name')
    	// ->where(['s.delivery_id'=>$delivery_id,'order_status'=>40])
    	->where("find_in_set($delivery_id,s.delivery_id) and order_status=40")
    	->paginate();
    	$arr = array();

    	foreach ($res as $key => $value) {
    		$value['list'] = Db::name('order_goods')->where('order_id',$value['order_id'])->select();
    		$value['sum'] = Db::table('sdzx_order_goods')->alias('og')->field('SUM(og.num) as sum')->where('order_id',$value['order_id'])->find();
    		$arr[] = $value;
    	}
    	// dump($arr);
    	$this->assign(['res'=>$arr,'page'=>$res->render()]);
    	return $this->fetch();
    }
    /* 配送单详情 */ 
    // public function details(){
    // 	$order_id = request()->param('order_id');
    // 	$list = Db::name('order_goods')->where('order_id',$order_id)->select();
    // 	// $this->assign('list',$list);
    // 	return $this->fetch('details',['list'=>$list]);
    // }

    // 退货
	public function refund(){
		if(request()->isPost()){
			$config = Config::get('wx');
            $con = array_merge($config['pay'], $config['xcx']);
            $con['notify_url'] = request()->domain().$con['notify_url'];
            $WxpaySdk = new WxpaySdk($con);
			$data = request()->only('order_id,order_goods_id,nums,remarks');
			// $order_status = db('order')->where('order_id',$data['order_id'])->value('order_status');
			// $res = db('order')->where('order_id',$data['order_id'])->setField('order_status',50);
			
			//日志记录
            Log::init(Config::get('log_refund'));

			$res = db('order')->where('order_id',$data['order_id'])->find();
			$shipping = db('shipping')->where('order_id',$data['order_id'])->find();
			$is_refund = db('shipping_refund')->where('order_id',$data['order_id'])->find();
			Db::startTrans();
			if(!$is_refund){
				$arr = [
					'order_id' 		=> $data['order_id'],			
					'order_no' 		=> $res['order_no'],			
					'buyer_id' 		=> $res['user_id'],			
					'buyer_name' 	=> $res['user_name'],			
					'agent_id' 		=> $res['agent_id'],			
					'agent_name' 	=> $res['agent_name'],			
					'delivery_id' 	=> $shipping['delivery_id'],			
					'delivery_name' => $shipping['delivery_name'],			
					'create_time' 	=> date('Y-m-d H:i:s')			
				];
				Db::name('shipping_refund')->insert($arr);
			}
			$goods = db('order_goods')->where('order_goods_id',$data['order_goods_id'])->find();
		
			$money = $data['nums']*$goods['price'];
			$_remark = "商品（{$goods['brand_name']}）{$goods['goods_name']}退货数量：{$data['nums']}";
			$map = [
				'order_id'			=> $data['order_id'],
				'user_id' 			=> $res['user_id'],
				'act_time' 			=> date('Y-m-d H:i:s'),
				'op_uid' 			=> $this->user['id'],
				'op_uname'			=> $this->user['username'],
				'order_status' 		=> $res['order_status'],
				'bop_order_status'	=> $res['order_status'],
				'op_model'			=> 'employee',
				'act_remark'     	=> '订单部分商品已退货，商品已支付金额将在3个工作日内退回||'.$_remark
			];
			$re = Db::name('order_action')->insert($map);
			if(!$re){
				Db::rollback();
				$this->error('操作失败');
			}
			$result = [
				'og_id' => $data['order_goods_id'],
				'order_id' => $data['order_id'],
				'order_no' => $res['order_no'],
				'goods_id' => $goods['goods_id'],
				'specval_id' => $goods['goods_specval_id'],
				'goods_name' => $goods['goods_name'],
				'rg_time' => date('Y-m-d H:i:s'),
				'rg_num' => $data['nums'],
				'rg_remark' => $data['remarks'],
				'return_money' => $goods['price']
			];
			$obj = Db::name('order_goods_return')->insertGetId($result);
			if(!$obj){
				Db::rollback();
				$this->error('操作失败');
			}

			$info = [
				'create_time'	=>	date('Y-m-d H:i:s'),
				'remark'		=> 	$data['remarks'],
				'money'			=>	$money,
				'order_id'		=>	$data['order_id'],
				'audit_type'	=>	1,
			];
			$add_audit = Db::name('order_refund_audit')->insertGetId($info);
			if(!$add_audit){
				Db::rollback();
				$this->error('操作失败');
			}

			$edit_return = Db::name('order_goods_return')->where('rg_id',$obj)->update(['audit_id'=>$add_audit]);
			if(!$edit_return){
				Db::rollback();
				$this->error('操作失败');
			}
			$edit = Db::name('order_goods')->where('order_goods_id',$data['order_goods_id'])->setDec('num',$data['nums']);
			if(!$edit){
				Db::rollback();
				$this->error('操作失败');
			}
			Db::commit();
           	$this->success('操作成功','refresh');
			// // 发起退款操作
   //          $refund_param = [
   //              'transaction_id' => $res['pay_no'],
   //              'out_refund_no'  => $obj.'_'.time(),
   //              'total_fee'      => $res['pay_money']*100,
   //              'refund_fee'     => $money*100,
   //              'op_user_id'     => $con['mchid']
   //          ];

   //          $refund = $WxpaySdk->refund($refund_param);

   //          Log::record('订单退货('.$data['order_id'].')-退货退款'.date('Y-m-d H:i:s'),'refund');
   //          Log::record($refund_param,'refund');
   //          Log::record($refund,'refund');

   //          if ($refund['return_code'] === 'SUCCESS' && $refund['result_code'] === 'SUCCESS') {
 		// 		$edit = db('order_goods')->where('order_goods_id',$data['order_goods_id'])->setDec('num',$data['nums']);
   //              Db::name('order_goods_return')->where('rg_id',$obj)->update(['pay_status'=>1]);
   //              Db::commit();
   //            	$this->success('操作成功','refresh');
   //          }else{
   //          	Db::rollback();
   //              Db::name('order_goods_return')->where('rg_id',$obj)->update(['error'=>var_export($refund,true)]);
   //              $this->error('操作失败');
   //          }
		}else{
			$order_goods_id = request()->param('order_goods_id');
			$order = db('order_goods')->where('order_goods_id',$order_goods_id)->find();
			// $order_goods = db('order_goods')->where('order_id',$order_id)->select();
			// $this->assign('order_goods',$order_goods);
			return view('refund',$order);
		}
	}

	//配送完成
	public function draw(){
		$order_no = input('order_no');												//获取订单号
		$addr=Request::instance()->post('addr');									//获取签名花板图片保存路径
		$order_no_new=Request::instance()->post('order_no');						//获取提交的订单号

		if($addr){
			$order = Db::name('order')->where('order_no',$order_no_new)->find();
			if ($order['order_status'] == 100) {
				$this->success('感谢您的签收');
			}
			Db::startTrans();
			$map = [
				'order_id' => $order['order_id'],
				'user_id' => $order['user_id'],
				'act_time' => date('Y-m-d H:i:s'),
				'op_uid' => $this->user['id'],
				'op_uname' => $this->user['username'],
				'order_status' => 100,
				'bop_order_status' => $order['order_status'],
				'op_model' => 'employee'
			];
			$re = Db::name('order_action')->insert($map);
			$time = date('Y-m-d H:i:s');
			$order_edit = Db::name('order')->where('order_no',$order_no_new)->setField(['order_status'=>100,'signature'=>$addr,'sign_time'=>$time,'finish_time'=>$time]);
			$shipping_edit = Db::name('shipping')->where('order_id',$order['order_id'])->setField(['shipping_status'=>2,'finish_time'=>$time]);
			if($re && $order_edit && $order_edit){
				Db::commit();
				$this->success('感谢您的签收');
			}else{
				Db::rollback();
				$this->error('操作失败');
			}
		}
		$this->assign('order_no',$order_no);
		return $this->fetch();
	}
}
